<template>
    <div class="app-container">
        <el-row>
          <el-col :span="12"></el-col>
        </el-row>
             <el-row :gutter="16">
                <!--所属机构-->
        <el-form :inline="true" :model="regulationsList" class="demo-form-inline" >
            <el-form-item label="所属机构">
                <treeselect v-model="queryParams.organization" :options="deptList" :show-count="true" placeholder="请选择所属机构" style="width:180px ;height: 20px;"/>
            </el-form-item>
                <el-form-item label="法律法规分类名称" >
                    <el-input v-model="queryParams.classification" placeholder="请输入法律法规名称" style="width:180px ; height:20px"></el-input>
                </el-form-item>
            <el-form-item label="状态">
                <el-select v-model="queryParams.status" placeholder="请选择状态" style="width: 180px ; height:20px;">
                    <el-option label="正常" value="0">正常</el-option>
                    <el-option label="停用" value="1">停用</el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleQuery">查询</el-button>
            </el-form-item>
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                
                @click="handleAdd"
                v-hasPermi="['aqsc:regualtions:add']"
              >新建</el-button>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-form>
          </el-row>
          <el-row>
            
            <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              
              @click="handleImport"

            >导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              
              @click="handleExport"

            >导出</el-button>
          </el-col>
          
          </el-row>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
          
          <el-table v-loading="loading" :data="regulationsList" @selection-change="handleSelectionChange" >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="所属机构" align="center" key="dept.deptName"  prop="dept.deptName" v-if="columns[0].visible" />
            <el-table-column label="编号" align="center" key="number" prop="number" v-if="columns[1].visible" :show-overflow-tooltip="true" />
            <el-table-column label="法律法规分类名称" align="center" key="classification"  prop="classification" v-if="columns[2].visible" :show-overflow-tooltip="true"/>
            <el-table-column label="状态标识" align="center" key="status" prop="status" v-if="columns[3].visible" width="120" :formatter="cz"/>
           
            <el-table-column
              label="操作"
              align="center"
              width="160"
              class-name="small-padding fixed-width">
              <template slot-scope="scope" v-if="scope.row.userId !== 1">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['aqsc:regulations:edit']"
                ></el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['aqsc:regulations:remove']"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
      <el-row>
        <el-col :span="2">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['aqsc:regulations:remove']"
              style="margin: 20px;"
            >批量删除</el-button>
          </el-col>
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
            style="float:right;"
          />
      </el-row>
      <!-- 添加或修改用户配置对话框 -->
      <el-dialog :title="title" :visible.sync="open"   append-to-body>
        <el-form ref="form" :model="form" :rules="rules" inline>
          <el-row>
            
              <el-form-item label="编号"  prop="number">
                <el-input v-model="form.number" placeholder=""  maxlength="40" />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="分类名称">
                <el-input v-model="form.classification" placeholder=""  maxlength="40" />
             </el-form-item>
          </el-row>
          
          <el-row>
            <el-col :span="12">
            <el-form-item label="状态">
                <el-radio-group v-model="form.status">
                  <el-radio label="0" >正常</el-radio>
                  <el-radio label="1" >停用</el-radio>
                </el-radio-group>  
            </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-dialog>
    
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
        

  </template>
  
  <script>
  
import { addRegulations, delRegulations, getRegulations, listRegulations, updateRegulations, getDeptList } from "@/api/system/regulations";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { number } from "echarts/lib/export";
  
    
  export default {
  
    components: { Treeselect},
    data() {
      let nameVaildate=(rule,value,callbabk)=>{
        fetchList({number:value}).then(res =>{
          let arr = res.data.data.records;
          for(let i=0;i<arr.length;i++){
          //如果是update,需要先排除自身
          if (this.form.number !=null &&arr[i].id ==this.form.id){
          arr.splice(i,1)
          }
          //console.log(arr)
          if(arr.length>0){
          callback('名字已经存在');
          }
        }
          callback();
        })
      }
      return {
        regulationsList:null,
        // 遮罩层
        loading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        //所属机构
        deptList: [],
        // deptOptions: [],
        // 总条数
        total: 0,
        // 用户表格数据
        userList: null,
        // 弹出层标题
        title: "",
        // 日期范围
        dateRange: [],
        // 是否显示弹出层
        open: false,
        // 岗位选项
        form: {
        },
        defaultProps: {
          children: "children",
          label: "label"
        },
        // 用户导入参数
        upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/aqsc/regulations/importData"
      },
        
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          dept:{

          }
        },
        // 列信息
        columns: [
          { key: 0, label: `所属机构`, visible: true },
          { key: 1, label: `编号`, visible: true },
          { key: 2, label: `法律法规分类名称`, visible: true },
          { key: 3, label: `状态标识`, visible: true }
        ],
        
      }
    },
      // form 表单校验

      rules: {

        number: [
          { required: true, message: '请输入编号', trigger: 'blur' },
          {validator: nameVaildate,trigger: 'blur'},
        ],
        classification: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
        ],
        status: [
          { required: true,message: '请选择状态'}
        ]
      },
    created(){
            this.getList();
            
            this.getDeptTree()
        },
    methods: {
        /**
         * dept查询
         */
        getDeptTree() {
            getDeptList().then(response => {
            this.deptList = response.data;

        });

        },
            // 多选框选中数据
        handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
        },
      /** 查询用户列表 */
      getList() {
        console.info(this.queryParams)

        this.loading = true;
        listRegulations(this.queryParams).then(response => {
            console.info(response)
            this.regulationsList = response.rows;
            this.total = response.total;
            this.loading = false;
          }
        );
      },
      cz:function(row){
          console.info(row)
          if(row.status==0){
            return "正常"
          }else if(row.status==1){
            return "停用"
          }
        },
     
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      // 表单重置
      reset() {
        this.form = {
          
        }},
      /** 新增按钮操作 */
      handleAdd() {
        if(this.queryParams.organization!=undefined){
        this.reset();
        this.form.organization=this.queryParams.organization
        this.open = true;
        this.title = "新建";
        this.form.type = this.deptId
    }else{
        this.$alert('请选择所属机构', {

        confirmButtonText: '确定',

});
    }
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids;
        getRegulations(id).then(response => {
          this.form = response;
          this.open = true;
          this.title = "修改"; 
          console.info(this.form.status)
        });
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {
              updateRegulations(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addRegulations(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const Ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除编号为"' + Ids + '"的数据项？').then(function() {
          return delRegulations(Ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      }, 
        /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "法律法规导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('aqsc/regulations/importTemplate', {
      }, `regulations_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
      /** 导出按钮操作 */
    handleExport() {
      this.download('aqsc/regulations/export', {
        ...this.queryParams
      }, `regulations_${new Date().getTime()}.xlsx`)
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
    }
  }
  </script>